package xin.marcher.module.rights.repository;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import xin.marcher.module.common.redis.RedisCache;
import xin.marcher.module.rights.domain.bo.EshopUserDetails;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Repository
public class LoginRepository {

    public static final String USER_DETAILS_KEY = "userDetailsKey";

    @Value("${eshop.tokenSecretKey}")
    public String tokenSecretKey;

    @Value("${eshop.loginInfoExpireTime}")
    public Integer loginInfoExpireTime;

    @Autowired
    private RedisCache redisCache;

    /**
     * 保存用户登录信息
     */
    public void saveUserDetails(String userDetailsKey, EshopUserDetails userDetails) {
        redisCache.set(userDetailsKey, JSON.toJSONString(userDetails), loginInfoExpireTime);
    }

    /**
     * 刷新登录信息的过期时间
     */
    public void renewLoginInfo(String userDeatilKey) {
        redisCache.expire(userDeatilKey, loginInfoExpireTime.longValue());
    }

    /**
     * 清除用户登录信息
     */
    public void invalidteLoginInfo(String token) {
        redisCache.delete(parseToekn(token));
    }

    /**
     * 生成颁发给用户的token
     */
    public String generateToken(String userDetailsKey) {
        Map<String, Object> map = new HashMap<>();
        map.put(USER_DETAILS_KEY, userDetailsKey);
        return Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS256, tokenSecretKey).compact();
    }

    /**
     * 从token中解析出来 userDetailsKey
     */
    public String parseToekn(String token) {
        Claims claims = Jwts.parser().setSigningKey(tokenSecretKey).parseClaimsJws(token).getBody();
        return (String) claims.get(USER_DETAILS_KEY);
    }

}
